import {defineStore} from 'pinia';
import {LoginApi} from '@/api/login';
import {constantRoutes} from '@/router';
import Layout from '@/layout/index.vue';
import {CacheUtil} from "@/utils/cacheUtil";

const modules = import.meta.glob('../../views/**/**.vue');

const permissionStore = defineStore('permissionStore', {
    state: () => ({
        routes: [],
        addRoutes: [],
        defaultRoutes: [],
        topBarRouters: [],
        sidebarRouters: [],
        permissions: [],
    }),
    getters: {
        getSidebarRouters() {
            return this.sidebarRouters;
        },
        getDefaultRoutes() {
            return this.defaultRoutes;
        },
    },
    actions: {
        //获取路由
        generateRoutes() {
            return new Promise((resolve, reject) => {
                LoginApi.getRouters()
                    .then(res => {
                        const rdata = JSON.parse(JSON.stringify(res.data));
                        const sdata = JSON.parse(JSON.stringify(res.data));
                        const sidebarRoutes = filterAsyncRouter(sdata);
                        const rewriteRoutes = filterAsyncRouter(rdata);
                        this.routes = constantRoutes.concat(rewriteRoutes);
                        this.addRoutes = rewriteRoutes;
                       // this.sidebarRouters = constantRoutes.concat(sidebarRoutes);
                        this.defaultRoutes = constantRoutes.concat(sidebarRoutes);
                        this.topBarRouters = sidebarRoutes;
                        resolve(rewriteRoutes);
                    })
                    .catch(error => {
                        CacheUtil.clear();
                        reject(error);
                    });
            });
        }
    }
});

function filterAsyncRouter( asyncRouterMap, lastRouter, type ) {
    return asyncRouterMap.filter(route => {
        if (route.hidden) {
            return false;
        }
        //首页
        if (route.path === '/index') {
            route.meta.affix = true;
        }
        if (type && route.children) {
            route.children = filterChildren(route.children, null);
        }
        if (route.component) {
            if (route.component === 'Layout') {
                route.component = Layout;
            } else {
                route.component = loadView(route.component);
            }
        }
        if (route.children !== null && route.children && route.children.length && route.type !== 2) {
            route.children = filterAsyncRouter(route.children);
        } else {
            delete route.children;
            delete route.redirect;
        }
        return true;
    });
}

function filterChildren(childrenMap, lastRouter) {
    let children = [];
    childrenMap.forEach(el => {
        if (el.children && el.children.length) {
            if (el.component === 'ParentView' && !lastRouter) {
                el.children.forEach((c) => {
                    c.path = el.path + '/' + c.path;
                    if (c.children && c.children.length) {
                        children = children.concat(filterChildren(c.children, c));
                        return;
                    }
                    children.push(c);
                });
                return;
            }
        }
        if (lastRouter) {
            el.path = lastRouter.path + '/' + el.path;
        }
        children = children.concat(el);
    });
    return children;
}

function loadView(view) {
    if (!view.endsWith("/index")) {
        view = view + "/index";
    }
    if (!view.startsWith("/")) {
        view = "/" + view;
    }
    const value = modules[`../../views${view}.vue`];
    if (value) {
        return value;
    } else {
        return modules[`../../views/error/404.vue`];
    }
}

export default permissionStore;
